package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.vo.user.UpdateLoginPwdVo;
import com.cssw.fyzb.busi.service.user.UserService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.cache.CacheKeys.forUpdateLoginPwd;
import static com.cssw.fyzb.busi.util.Bizs.ERROR_FORMAT_LOGIN_PWD;
import static com.cssw.fyzb.busi.util.Bizs.USER_NOT_EXISTS;

/**
 * @author Feng Chen
 */
@Function(description = "修改密码", parameters = {
        @Parameter(name = "mobile", type = Type.Integer, description = "手机号", required = true),
        @Parameter(name = "loginPwd", type = Type.Integer, description = "登录密码", required = true)
})
@Component
public class UpdateLoginPwd implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    private static final Logger logger = LoggerFactory.getLogger(UpdateLoginPwd.class);

    @Override
    public Response execute(Request request) throws Exception {
        String mobile = request.getString("mobile");
        String loginPwd = request.getString("loginPwd");
        try {
            UpdateLoginPwdVo updateLoginPwdVo = simpleCache.get(forUpdateLoginPwd(mobile));
            if (loginPwd == null || loginPwd.length() < 6 || loginPwd.length() > 18) {
                return Response.fail(ERROR_FORMAT_LOGIN_PWD.message, ERROR_FORMAT_LOGIN_PWD.code);
            }
            if (updateLoginPwdVo == null) {
                logger.error("缓存不存在或者已失效");
                return Response.fail("缓存不存在或者已失效");
            }
            User user =userService.getByMobile(mobile);
            if ( user== null) {
                return Response.fail(USER_NOT_EXISTS.message, USER_NOT_EXISTS.code);
            }

            userService.updateLoginPwd(user.getUserId(),mobile, loginPwd);
            return Response.success();
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("更新用户登录密码失败");
        }
    }

}
